﻿using System;
using System.Device.Location;
using System.IO.IsolatedStorage;
using System.Windows;



namespace BootyShaker.Utils
{
    public class GPS
    {
        static GeoCoordinateWatcher watcher = null;
        void watcher_StatusChanged(object sender, GeoPositionStatusChangedEventArgs e)
        {
            Deployment.Current.Dispatcher.BeginInvoke(() => MyStatusChanged(e));
        }

        void MyStatusChanged(GeoPositionStatusChangedEventArgs e)
        {
            switch (e.Status)
            {
                case GeoPositionStatus.Disabled:
                    if (watcher.Permission == GeoPositionPermission.Denied)
                    {

                        //TODO: Try to get previous location from app settings
                        //  "You have disabled teh location Service on your device.\n";
                    }
                    else
                    {
                        // "Location is not functioning on this device\n";
                    }
                    break;
                case GeoPositionStatus.Initializing:
                    //"Location service is initializing...\n";

                    break;
                case GeoPositionStatus.NoData:
                    //"Location data is not available.\n";

                    break;
                case GeoPositionStatus.Ready:
                    //"Location data is available.\n";

                    break;
            }
        }

        void watcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
        {
            Deployment.Current.Dispatcher.BeginInvoke(() => MyPositionChanged(e));
        }

        void MyPositionChanged(GeoPositionChangedEventArgs<GeoCoordinate> e)
        {
            lock (App.operationSyncLock)
            {
                if (IsolatedStorageSettings.ApplicationSettings.Contains("GPSLocationLatitude"))
                {
                    IsolatedStorageSettings.ApplicationSettings["GPSLocationLatitude"] = e.Position.Location.Latitude;
                }
                else
                {
                    IsolatedStorageSettings.ApplicationSettings.Add("GPSLocationLatitude", e.Position.Location.Latitude);
                }

                if (IsolatedStorageSettings.ApplicationSettings.Contains("GPSLocationLongitude"))
                {
                    IsolatedStorageSettings.ApplicationSettings["GPSLocationLongitude"] = e.Position.Location.Longitude;
                }
                else
                {
                    IsolatedStorageSettings.ApplicationSettings.Add("GPSLocationLongitude", e.Position.Location.Longitude);
                }
                IsolatedStorageSettings.ApplicationSettings.Save();
            }
            watcher.Stop();
            //Location l = new Location()
            //{
            //    Latitude = e.Position.Location.Latitude,
            //    Longitude = e.Position.Location.Longitude,
            //    Altitude = e.Position.Location.Altitude

            //};

            //ReverseGeocodeAddress(l);
        }

        public GPS()
        {

            try
            {

                if (watcher == null)
                {
                    watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.Default);
                    watcher.MovementThreshold = 20; // 20 meters. 
                    watcher.StatusChanged += new EventHandler<GeoPositionStatusChangedEventArgs>(watcher_StatusChanged);
                    watcher.PositionChanged += new EventHandler<GeoPositionChangedEventArgs<GeoCoordinate>>(watcher_PositionChanged);
                }
                watcher.Start();

            }
            catch 
            {

            }
        }
        //public static void ReverseGeocodeAddress(Location location)
        //{
        //    // Get credentials and only then place an async call on the geocode service.

        //    var request = new ReverseGeocodeRequest()
        //    {
        //        // Pass in credentials for web services call.


        //        Culture = System.Globalization.CultureInfo.CurrentUICulture.Name,
        //        Location = location,

        //        // Don't raise exceptions.
        //        ExecutionOptions = new Geocode.ExecutionOptions
        //        {
        //            SuppressFaults = true
        //        },
        //    };
        //    request.Credentials = new Credentials();
        //    request.Credentials.ApplicationId = App.BingMapsID;

        //    var binding = new BasicHttpBinding(BasicHttpSecurityMode.Transport);
        //    binding.MaxReceivedMessageSize = int.MaxValue;
        //    binding.MaxBufferSize = int.MaxValue;
        //    var serviceUri = new UriBuilder(@"http://dev.virtualearth.net/webservices/v1/geocodeservice/geocodeservice.svc");
        //    serviceUri.Scheme = Uri.UriSchemeHttps;
        //    serviceUri.Port = -1;

        //    var geocodeClient = new GeocodeServiceClient(binding, new EndpointAddress(serviceUri.Uri));
        //    geocodeClient.ReverseGeocodeCompleted += new EventHandler<ReverseGeocodeCompletedEventArgs>((o, e) =>
        //    {
        //        try
        //        {
        //            if (e.Result.ResponseSummary.StatusCode != Geocode.ResponseStatusCode.Success ||
        //                e.Result.Results.Count == 0)
        //            {
        //                // Report geocode error.
        //                //Dispatcher.BeginInvoke(() => error(new GeocodeError(e)));
        //            }
        //            else
        //            {
        //                ReverseGeocodeSuccess(e.Result.Results);

        //                //e.Result.Results.
        //                //Dispatcher.BeginInvoke(() => completed(e.Result.Results));
        //            }
        //        }
        //        catch (Exception ex)
        //        {
        //            throw ex;
        //        }
        //    });
        //    //ReverseGeocodeCompleted(o, e));
        //    geocodeClient.ReverseGeocodeAsync(request);

        //}
        ////}

        ////private static void ReverseGeocodeCompleted(object sender, ReverseGeocodeCompletedEventArgs e)
        ////{

        ////}
        //private static void ReverseGeocodeSuccess(ICollection<GeocodeResult> res)
        //{
        //    try
        //    {
        //        var address = res.FirstOrDefault();
        //        if (address != null)
        //        {
        //            if (IsolatedStorageSettings.ApplicationSettings.Contains("GPSLocationInfo"))
        //            {
        //                IsolatedStorageSettings.ApplicationSettings["GPSLocationInfo"] = address.Address;
        //            }
        //            else
        //            {
        //                IsolatedStorageSettings.ApplicationSettings.Add("GPSLocationInfo", address.Address);
        //            }
        //        }
        //    }
        //    catch (Exception ex) { }
        //}

    }
}
